<template>
  <Dialog :title="title" :model-value="visible" width="600px" :before-close="closeForm">
    <unitDeptTree ref="deptTree" v-model="chioseId" :is-multiple="true" :checkstrictly="true" />
    <p v-if="chioseId.length == 0" style="color: #f56c6c; text-align: center">
      至少选择一个部门!
    </p>
    <template #footer>
      <el-space style="text-align: center">
        <el-button :disabled="chioseId.length == 0" type="primary" @click="save">保存</el-button>
        <el-button @click="closeForm">取消</el-button>
      </el-space>
    </template>
  </Dialog>
</template>

<script>
import { Dialog } from '@/components/Dialog'
import { unitDeptTree } from '@/components/unit/'
import * as deptPowerApi from '@/api/unit/deptPower'
import { useUserStoreWithOut } from '@/store/modules/user'
const userStore = useUserStoreWithOut()
export default {
  components: {
    unitDeptTree,
    Dialog
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    empId: {
      type: String,
      default: null
    },
    title: {
      type: String,
      default: '设定用户部门数据权限'
    }
  },
  data() {
    return {
      chioseId: []
    }
  },
  computed: {
    comId() {
      return userStore.comId
    }
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.load()
        }
      },
      immediate: true
    }
  },
  methods: {
    async load() {
      const list = await deptPowerApi.get(this.empId, this.comId)
      if (list) {
        this.chioseId = list
      } else {
        this.chioseId = []
      }
    },
    async save() {
      if (this.chioseId.length === 0) {
        return
      }
      await deptPowerApi.set(this.empId, this.comId, this.chioseId)
      this.$message({
        type: 'success',
        message: '设置成功!'
      })
      this.$emit('update:visible', false)
      this.$emit('close', true)
    },
    closeForm() {
      this.$emit('update:visible', false)
      this.$emit('close', false)
    }
  }
}
</script>
